
let connection = null
let status = false

let roomId = ""
let userId = ""

let roomReferenceData = {

    roomId:"",
    userId:"",
    loginStatus:false,
    userList:[],
    newUserList:[],
    wsUrl:"",
    localStream:null,
    mediaSrc:"",
}


wsUrl = "ws://127.0.0.1:3347";
WssUrl = "wss://127.0.0.1:2347/";

window.onload = function (event) {

    // console.log(event)
    let ip = event.target.domain
    wsUrl = "wss://" + ip + "/ws/"
}

function EnterRoom() {

    let roomServer = document.getElementById("room_server").value;
    if (roomServer.length !== 0) {

        roomReferenceData.wsUrl = roomServer
    } else {

        roomReferenceData.wsUrl = wsUrl
    }

    roomId = document.getElementById('room_id').value;
    userId = document.getElementById('user_id').value;

    roomReferenceData.roomId = roomId
    roomReferenceData.userId = userId

    document.getElementById('enter_room').disabled = true
    document.getElementById("left_room").disabled  = false
    document.getElementById("publish_stream_status").disabled = false

    console.log(document.getElementById("video_option").value)

    roomReferenceData.mediaSrc = document.getElementById("video_option").value
    // connect to websocket server
    Start()
}

function LeftRoom() {

    document.getElementById("publish_stream_status").disabled = true
    StopLocalMedia(roomReferenceData)
    // send user_out to server
    PostMessageToWebsocket(UserOutReq(roomReferenceData.roomId, roomReferenceData.userId))
    connection.close()
    connection = null
}

async function PublishStreamStatus()
{
    if (roomReferenceData.mediaSrc === "screen_desktop") {

        let stream = await navigator.mediaDevices.getDisplayMedia(containers)
        roomReferenceData.localStream = stream;

    } else {

        let stream = await navigator.mediaDevices.getUserMedia(containers)
        roomReferenceData.localStream = stream;
    }

    let localVideo = document.getElementById('local_video');
    localVideo.srcObject = roomReferenceData.localStream
    localVideo.play()

    let message = PublishStreamReq(roomReferenceData, true)
    PostMessageToWebsocket(message)

    document.getElementById("publish_stream_status").disabled = true

    return true
}

 function Start(){

    if (roomId.length === 0 || userId.length === 0 || roomReferenceData.wsUrl.length === 0) {

        alert("RoomId or UserId is empty!!!")
        document.getElementById('enter_room').disabled = false
        document.getElementById("left_room").disabled  = true
        return
    }
    if ('WebSocket' in window)
    {
        connection = new WebSocket(roomReferenceData.wsUrl);
        connection.onerror = function (event) {

            console.log("[onerror]")
            console.log(event);
            document.getElementById('enter_room').disabled = false
            document.getElementById("left_room").disabled  = true
            StopLocalMedia(roomReferenceData)
            connection = null
        }
        connection.onopen = async function (event) {

            console.log("[onopen]")
            console.log(event)

            // start send user_in_req to signal server
            let msg = UserInReq(roomId, userId)
            PostMessageToWebsocket(msg)
        }
        connection.onmessage = function (message) {

            OnMessageCallback(message)
        }
        connection.onclose = function (event) {

            console.log("onclose")
            console.log(event)
            document.getElementById('enter_room').disabled = false
            document.getElementById("left_room").disabled  = true

            StopLocalMedia(roomReferenceData)
            connection = null
        }
    }
    else
    {
        alert("no support websocket protocol");
    }
}

function OnMessageCallback(message) {

    let jsonMessage = JSON.parse(message.data)
    if (jsonMessage == null) {

        return;

    } else if (jsonMessage.header.result !== 0) {

        alert("error result : " + jsonMessage.header.result)
        return
    }
    switch(jsonMessage.header.msg_type)
    {
        case "user_in_res":
        {
            ProcessUserInReq(roomReferenceData, jsonMessage)
            break
        }
        case "get_publish_stream_status_res":
        {
            GetPublishStreamStatusRes(roomReferenceData, jsonMessage)
            break
        }
        case "user_in_bcast":
        {
            ProcessUserInBcast(roomReferenceData, jsonMessage)
            break
        }
        case "user_out":
        {
            ProcessUserOut(roomReferenceData, jsonMessage)
            break
        }
        case "get_publish_list":
        {
            GetPublishListResponse(roomReferenceData, jsonMessage)
            break
        }
        case "heart_beat":
        {
            PostMessageToWebsocket(HeartBeat(roomReferenceData))
            break
        }
        case "subscribe_res":
        {
            //SubscribeRes(roomReferenceData, jsonMessage)
            break
        }
        case "subscribe_target":
        {
            SubscribeTarget(roomReferenceData, jsonMessage)
            break
        }
        case "publish_res":
        {
            PublishResponse(roomReferenceData, jsonMessage)
            break
        }
        case "publish_bcast":
        {
            PublishBroadcast(roomReferenceData, jsonMessage)
            break
        }
        case "publish_target":
        {
            PublishTarget(roomReferenceData, jsonMessage)
            break
        }
        case "ice_candidate_target":
        {
            CandidateTarget(roomReferenceData, jsonMessage)
            break
        }
        case "send_answer_target":
        {
            SetRemoteDescription(roomReferenceData, jsonMessage)
            break
        }
    }
}

function PostMessageToWebsocket(message) {

    if (connection != null) {

        connection.send(message)
    }
}






